package org.example.esdemo.runner;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.esdemo.entity.Product;
import org.example.esdemo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;

@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private ProductService productService;

    @Override
    public void run(String... args) throws Exception {
        loadInitialData();
    }

    private void loadInitialData() throws IOException {
        ClassPathResource resource = new ClassPathResource("data.json");
        ObjectMapper objectMapper = new ObjectMapper();
        Product[] products = objectMapper.readValue(resource.getInputStream(), Product[].class);

        if (products != null && products.length > 0) {
            productService.saveAllProducts(Arrays.asList(products));
            System.out.println("初始数据加载成功");
        }
    }
}